<template>
	<view class="bg-login">
		<view :style="{'height':marTop}"></view>
		<view class="login-box">
			<view class="title">
				欢迎加入优图!
			</view>
			<view class="content">
				请选择你的登陆方式，首次登录会自动创建账号!
			</view>
			<view style="width: 360rpx;margin: auto;height: 32rpx;">
				<uv-button @click="getUserProfile" :custom-style="customStyle" type="success" iconSize="64rpx"
					iconColor="white" icon="weixin-circle-fill" text="微信一键登录"></uv-button>
			</view>
			<view class="test" @click="toTestAccount">
				测试账号
			</view>
		</view>
	</view>
	<uv-toast ref="toast"></uv-toast>
</template>

<script setup>
	import {
		useLayouterStore
	} from '@/stores/layouter';
	import {
		useUserStore
	} from '@/stores/user';
	const userStore = useUserStore()
	import {
		ref
	} from 'vue'
	import api from './api';
	const layouterStore = useLayouterStore()
	const marTop = ((layouterStore.screenHeight - 400) / 2) + 'rpx'
	const toast = ref(null);
	const customStyle = () => {
		return {
			borderRadius: '40rpx',
			width: '360rpx',
			margin: 'auto'
		}
	}
	const getUserProfile = () => {
		uni.getUserProfile({
			desc: "获取你的昵称、头像",
			success: (res) => {
				console.log(res);
				if (res.errMsg == "getUserProfile:ok" && res.userInfo != undefined) {
					getUserCode()
				}
			}
		})
	}
	const getUserCode = () => {
		uni.login({
			provider: "weixin",
			success: (res) => {
				loginByWeChat({
					code: res.code,
					avatar: '032c2955-3343-46a2-bdd5-9224c58f6beb'
				})
			}
		})
	}

	const loginByWeChat = (data) => {
		console.log(data);
		api.loginByWeChat(data).then(res => {
			console.log(res);
			if (res.successed) {
				userStore.token = res.token
				api.getInfo().then(res => {
					userStore.avatar = res.data.avatar
					userStore.nickName = res.data.nickName
				})
				toast.value.show({
					message: '登录成功！',
					type: 'success',
					duration: 800,
					position: 'top'
				});
				uni.navigateBack()
			} else {
				uni.navigateTo({
					url: '/pages/login/wechat'
				})
			}
		})
	}
	
	const toTestAccount  = ()=>{
		uni.navigateTo({
			url:'/pages/login/testAccount'
		})
	}
</script>

<style lang="scss">
	.bg-login {
		height: 100vh;
		background-color: #4c4c4c;

		.login-box {
			width: 90%;
			margin: auto;
			height: 400rpx;
			background-color: white;
			border-radius: 20rpx;

			.title {
				font-size: 36rpx;
				font-weight: bold;
				text-align: center;
				padding-top: 80rpx;
			}

			.content {
				color: #555;
				font-size: 24rpx;
				padding: 40rpx;
				text-align: center;
			}
			.test{
				font-size: 28rpx;
				    margin-left: 10rpx;
				    width: 120rpx;
				    border-bottom: 1px #00a4ff solid;
			}
		}
	}
</style>